package cn.xspace.module.other.http.impl;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonSyntaxException;
import com.xspace.android.xafcommon.been.MAreaBean;
import com.xspace.android.xafcommon.network.message.AResponseMsg;
import com.xspace.android.xafcommon.network.message.SendRequestListener;

import android.util.Log;
import cn.xspace.module.other.http.NetControl;
import cn.xspace.module.other.http.resp.QueryUnionAreaResp;

public class QueryUnionAreaImpl implements SendRequestListener {
	IQueryUnionArea mCallback;
	NetControl netControl;
	
	public QueryUnionAreaImpl() {
		super();
		netControl=new NetControl(this);
	}

	@Override
	public void offline(String arg0) {
		// TODO Auto-generated method stub

	}

	List<MAreaBean> list = new ArrayList<MAreaBean>();
	@Override
	public void requestResult(int arg0, AResponseMsg arg1) {
		QueryUnionAreaResp resp = (QueryUnionAreaResp) arg1;
		if ("0".equals(resp.code)) {
			try {
				JSONObject jsn=new JSONObject(resp.jsondata);
				JSONArray jarr1=jsn.getJSONArray("msg");
				parsrJson(jarr1);
			} catch (JsonSyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		//BaseDbMg.getInstance().getAreaDBBiz().MoreInsert(list);
		}
		Log.i("Area", "QueryUnionAreaImpl list size:"+list.size());
		mCallback.onQueryUnionArea(resp.code, list);
	}
	
	private void parsrJson(JSONArray jarr) {
		if(jarr==null)  return;
		for (int i = 0; i < jarr.length(); i++) {
			JSONObject job;
			try {
				job = jarr.getJSONObject(i);
				String name=job.getString("name");
				String id=job.getString("id");
				String parentcode=job.optString("parentcode");
				int level=job.getInt("level");
				String isleaf=job.getString("isleaf");
				MAreaBean mab=new MAreaBean(id, name, parentcode, isleaf, level+"");
				list.add(mab);
				//if(level<3){
					//JSONArray jarr1=job.optJSONArray("childList");
					//parsrJson(jarr1);
				//}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	public void sendQueryUnionArea(String pid,IQueryUnionArea callback) {
		this.mCallback = callback;
		list.clear();
		netControl.sendQueryUnionArea(pid);
	}

	public interface IQueryUnionArea {
		void onQueryUnionArea(String code, List<MAreaBean> list);
	}
	
	
}
